<?php
namespace tp5_lib\cron\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use tp5_lib\install\logic\Module;

class Cron extends Command
{
    protected function configure()
    {
        $this->setName('cron')->setDescription('Simple Daily Task Timer');
    }

    protected function execute(Input $input, Output $output)
    {
        chdir("public");
        $time=time();
        $module=new Module();
        if(!$log=$module->read("cron_log")){
            $log=[
                "cron"=>[],
                "task"=>[],
            ];
        }
        $log["last_run_time"]=$time;

        //读取任务列表并执行
        $message=[];
        if(!$tasks=$module->read("cron_task")){
            $log["error"]=$module->getError();
            $module->write("cron_log",$log);
            exit;
        }
        foreach($tasks as $task){
            //检查是否达到执行周期
            if(isset($log["task"][$task["id"]])){
                if(($log["task"][$task["id"]] + $task["period"]) > $time){
                    continue;
                }
            }
            $log["task"][$task["id"]] = $time;

            //执行操作
            $object=new $task["class"];
            if(!method_exists($object,$task["method"])){
                $message[] = $task["title"] . " 方法不存在";
                continue;
            }
            try {
                $result=call_user_func_array([$object,$task["method"]],$task["params"]);
                if(!$result){
                    $message = $task["title"] . ":" . $object->getError();
                    continue;
                }
                $message[] = $task["title"] . " 运行正常";
            } catch (\Exception $th) {
                $message[] = $task["title"] . " 运行失败";
                continue;
            }
        }

        //创建运行记录,保留最近10条
        $record=["code"=>1,"time"=>$time,"message"=>$message];
        $count=count($log["cron"]);
        if($count >= 10){
            $log["cron"]=array_slice($log["cron"],$count-9);
        }
        $log["cron"][]=$record;
        $module->write("cron_log",$log);
    }
}
